import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { Act } from '@/types/loginType'

export const useLocalStorageStore = defineStore('LocalStorageStore', () => {
  const accounts = ref<Act[]>([])

  getAll()
  // 操作 账号的四个方法
  // 读取全部的值
  function getAll() {
    const value = localStorage.getItem('aLis')
    accounts.value = value !== null ? JSON.parse(value) : new Array()
  }

  // 添加一条数据
  function setLocal(act: Act) {
    // 判断是否为已有数据
    const result = accounts.value.find((item) => act.id === item.id)
    if (!!result && true) {
      return false
    }
    accounts.value.push(act)
    const str = JSON.stringify(accounts.value)
    localStorage.setItem('aLis', str)
    const set = setToken(act.token)
    if (!set) {
      return false
    }
    return true
  }
  // 移除一个数据
  function removeLocal(index: string) {
    accounts.value.forEach((item, i) => {
      if (index === item.id) {
        accounts.value.splice(i, 1)
        const str = JSON.stringify(accounts.value)
        localStorage.setItem('aLis', str)

        if (accounts.value.length === 0) {
          localStorage.removeItem('aLis')
        }
        return true
      }
    })
  }
  // 移除所有数据
  function clearLocal() {
    localStorage.removeItem('aLis')
    return true
  }

  // cookie
  function setCookie(name: string, value: string, days: number) {
    let expires: string = ''
    if (days) {
      const date: Date = new Date()
      date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
      expires = '; expires=' + date.toUTCString()
    }
    document.cookie = name + '=' + (value || '') + expires + '; path=/'
  }

  // token
  function setToken(token: string) {
    try {
      localStorage.setItem('token', token)
      return true
    } catch (error) {
      return false
    }
  }

  function removeToken() {
    try {
      localStorage.removeItem('token')
      return true
    } catch (error) {
      return false
    }
  }

  return { accounts, setLocal, removeLocal, clearLocal, setCookie, setToken, removeToken }
})
